package binarytree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/19 10:03
 * https://leetcode-cn.com/problems/binary-tree-right-side-view/
 * 给定一个二叉树的 根节点 root，想象自己站在它的右侧，按照从顶部到底部的顺序，返回从右侧所能看到的节点值。
 */
public class RightSideView {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> rightSideView(TreeNode root) {
        Queue<TreeNode> levelQueue = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        if (root != null) {
            levelQueue.offer(root);
        }
        while (!levelQueue.isEmpty()) {
            int size = levelQueue.size();
            //只留每一层最后一个节点
            while (size > 0) {
                TreeNode poll = levelQueue.poll();
                if (size == 1) {
                    result.add(poll.val);
                }
                if (poll.left != null) {
                    levelQueue.offer(poll.left);
                }
                if (poll.right != null) {
                    levelQueue.offer(poll.right);
                }
                size--;
            }
        }
        return result;
    }

    public static void main(String[] args) {

    }
}
